# -*- coding: utf-8 -*-

from openai import OpenAI
from flask import Flask, request, jsonify
import base64

app = Flask(__name__)

@app.route('/image_recognition', methods=['POST'])
def image_recognition():
    try:
        # 从请求中获取 JSON 数据
        data = request.get_json()

        # 从请求中获取 api_key
        api_key = data.get('api_key')
        if not api_key:
            return jsonify({"error": "Missing 'api_key' in request."}), 400

        # 从请求中获取 Base64 编码的图片
        base64_image = data.get('base64_image')
        if not base64_image:
            return jsonify({"error": "Missing 'base64_image' in request."}), 400

        # 初始化 OpenAI 客户端
        client = OpenAI(
            api_key=api_key,
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )

        # 调用 OpenAI API 进行图像识别
        completion = client.chat.completions.create(
            model="qwen-vl-plus",
            messages=[
                {
                    "role": "system",
                    "content": [{"type": "text", "text": "You are a helpful assistant."}]
                },
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {"url": f"data:image/png;base64,{base64_image}"},
                        },
                        {"type": "text", "text": "图中描绘的是什么物品，不要输出其他任何信息， 直接告诉我物品名称和品牌，品牌无法识别就不返回，简明扼要"},
                    ],
                }
            ],
        )

        # 返回识别结果
        result = completion.choices[0].message.content
        return jsonify({"result": result})

    except Exception as e:
        return jsonify({"error": str(e)}), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5230)